package com.atguigu.juc.homework1;


class Number{
    private int number = 0;

    public synchronized void add(){
        //1.判断
        while (number!=0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //2.干活
        System.out.println(Thread.currentThread().getName()+"---"+(++number));
        //3.通知
        this.notifyAll();
    }

    public synchronized void sub(){
        //1.判断
        while (number==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //2.干活
        System.out.println(Thread.currentThread().getName()+"---"+(--number));
        //3.通知
        this.notifyAll();
    }
}
/**
 *
 有一个初始值为零的变量，现有两个线程对该变量操作，实现一个线程对变量加1，实现一个线程对变量减1,交替来10轮
 1.线程    操作     资源类
 2.判断   干活    通知
 3.防止虚假传唤用while条件
 */
public class ThreadCommunication {
    public static void main(String[] args) {
        Number number = new Number();
        new Thread(() -> { for (int i = 0; i <10 ; i++) { number.add();} },"A").start();

        new Thread(() -> { for (int i = 0; i <10 ; i++) { number.sub();} },"B").start();

        new Thread(() -> { for (int i = 0; i <10 ; i++) { number.add();} },"C").start();

        new Thread(() -> { for (int i = 0; i <10 ; i++) { number.sub();} },"D").start();
    }
}
